﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Payroll.Common.Utils;
using Payroll.BusinessLogic.Caching;
using Payroll.BusinessLogic.Data;
using Payroll.Common;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace Payroll.BusinessLogic.CustomerManager
{
    public partial class CustomerService : ICustomerService
    {
        #region Fields

        /// <summary>
        /// Object context
        /// </summary>
        private readonly PayrollHRDataContext m_context;

        /// <summary>
        /// Cache manager
        /// </summary>
        private readonly ICacheManager _cacheManager;
        /// <summary>
        /// Gets the local image path
        /// </summary>
        public string LocalImagePath
        {
            get
            {
                string path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\Customer";
                return path;
            }
        }
        /// <summary>
        /// Gets a local thumb image path
        /// </summary>
        public string LocalThumbImagePath
        {
            get
            {
                string path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\thumbs";
                return path;
            }
        }
        /// <summary>
        /// Gets an image quality
        /// </summary>
        public long ImageQuality
        {
            get
            {
                return 100L;
            }
        }
        private int LocalPicel
        {
            get { return 189; }
        }
        #endregion

        #region Ctor

        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="context">Object context</param>
        public CustomerService(PayrollHRDataContext context)
        {
            this.m_context = context;
            this._cacheManager = new PayrollRequestCache();
        }

        #endregion
        #region Methods
        public int Save(Customer c)
        {
            var item = (from cust in m_context.Customers
                        where cust.CustomerID == c.CustomerID
                        select cust).FirstOrDefault();

            bool flag = true;
            string caseWord = c.CustCaseWork.Length > 0 ? c.CustCaseWork : this.GetCaseWork(c.CutomerTypeId);
            if (!CommonHelper.IsNull(item))
            {
                flag = false;
            }

            while (flag)
            {
            Search:
                var query = (from ce in m_context.Customers
                             where ce.CutomerTypeId == c.CutomerTypeId && ce.CustCaseWork == caseWord
                             select ce).FirstOrDefault();
                if (CommonHelper.IsNull(query))
                {
                    flag = false;
                }
                else
                {
                    this.UpdateCustomerLastId(c.CutomerTypeId);
                    caseWord = this.GetCaseWork(c.CutomerTypeId);
                    goto Search;
                }
            }

            if (c.MimeType.Length > 0)
            {
                c.imageUrl = this.SavePictureInFile(c.CustCaseWork, c.PictureBinary, c.MimeType, c.imageUrl);
            }
            c.CustName = c.CustName.ToUpper();

            if (CommonHelper.IsNull(item))
            {
                item = new BusinessLogic.Data.Customer
                                                       {
                                                           #region Assign
                                                           CustomerID = c.CustomerID,
                                                           CustName = CommonHelper.Truncate(c.CustName, 128),
                                                           CustCaseWork = caseWord,
                                                           CustDate = CommonHelper.ToDate(c.CustDate),
                                                           CustHour = c.CustHour,
                                                           CustDateOfBirth = c.CustDateOfBirth,
                                                           CustPlate = CommonHelper.Truncate(c.CustPlate, 256),
                                                           CustParent = c.CustParent,
                                                           CustEmail = c.CustEmail,
                                                           CustAddres = c.CustAddres,
                                                           CustCompany = c.CustCompany,
                                                           CustMobile = c.CustMobile,
                                                           CustPhone = c.CustPhone,
                                                           CustEdu = c.CustEdu,
                                                           CustFax = c.CustFax,
                                                           CustLangue = c.CustLangue,
                                                           CustCareer = c.CustCareer,
                                                           isVisa = c.isVisa,
                                                           NationalId = c.NationalId,
                                                           CustYear = c.CustYear,
                                                           VisaNumber = c.VisaNumber,
                                                           isTravel = c.isTravel,
                                                           TravelNation = c.TravelNation,
                                                           TravelNote = CommonHelper.Truncate(c.TravelNote, 128),
                                                           CustSource = c.CustSource,
                                                           IsStudy = c.IsStudy,
                                                           CustNationalId = c.CustNationalId,
                                                           CustCity = c.CustCity,
                                                           CustState = c.CustState,
                                                           CustLevel = c.CustLevel,
                                                           CustStady = c.CustStady,
                                                           CustSchool = c.CustSchool,
                                                           CustRelative = c.CustRelative,
                                                           CustRelativeAddre = c.CustRelativeAddre,
                                                           CustNote = CommonHelper.Truncate(c.CustNote, 128),
                                                           CustFollowUpDate01 = c.CustFollowUpDate01,
                                                           CustFollowUpDate02 = c.CustFollowUpDate02,
                                                           CustFollowUpDate03 = c.CustFollowUpDate03,
                                                           CustNewNex01 = c.CustNewNex01,
                                                           CustNewNex02 = c.CustNewNex02,
                                                           CustNewNex03 = c.CustNewNex03,
                                                           CustIsDate = c.CustIsDate,
                                                           CustSignature = c.CustSignature,
                                                           studyTravelOther = c.studyTravelOther,
                                                           ProDate = CommonHelper.ToDate(c.ProDate),
                                                           ProCurator = c.ProCurator,
                                                           ProFullName = c.ProFullName,
                                                           ProSource = c.ProSource,
                                                           ProSchool = c.ProSchool,
                                                           ProProgram = c.ProProgram,
                                                           ProDateOfAdmission = CommonHelper.ToDate(c.ProDateOfAdmission),
                                                           ProscheduledInterviewDate = CommonHelper.ToDate(c.ProscheduledInterviewDate),
                                                           ProOther = c.ProOther,
                                                           ProBaccalaureate = c.ProBaccalaureate,
                                                           ProGraduateIndustry = c.ProGraduateIndustry,
                                                           ProGraduateYear = c.ProGraduateYear,
                                                           ProWorking = c.ProWorking,
                                                           ProLearning = c.ProLearning,
                                                           Deleted = false,
                                                           UpdateByID = c.UpdateByID,
                                                           CreateByID = c.CreateByID,
                                                           CreatedOn = c.CreatedOn,
                                                           UpdatedOn = c.UpdatedOn,
                                                           CutomerTypeId = c.CutomerTypeId,
                                                           ProFinanCapital = c.ProFinanCapital,
                                                           ProFinanIndustry = c.ProFinanIndustry,
                                                           ProFinanOther = c.ProFinanOther,
                                                           ProFinanRental = c.ProFinanRental,
                                                           ProFinanShipPapers = c.ProFinanShipPapers,
                                                           ProPropertyAccountValue = c.ProPropertyAccountValue,
                                                           ProPropertyCar = c.ProPropertyCar,
                                                           ProPropertyLand = c.ProPropertyLand,
                                                           ProPropertyOther = c.ProPropertyOther,
                                                           statusVisa = c.statusVisa,
                                                           businesstype = CommonHelper.Truncate(c.businesstype, 128),
                                                           busRealEstateInfo = c.busRealEstateInfo,
                                                           busRealMonthlyTax = c.busRealMonthlyTax,
                                                           busMontlyIncome = c.busMontlyIncome,
                                                           busOther = CommonHelper.Truncate(c.busOther, 128),
                                                           requirements = CommonHelper.Truncate(c.requirements, 256),
                                                           payment_1 = c.payment_1,
                                                           payment_2 = c.payment_2,
                                                           payment_accountNumber = c.payment_accountNumber,
                                                           payment_financial = c.payment_financial,
                                                           payment_AN = c.payment_AN,
                                                           payment_GD = c.payment_GD,
                                                           payment_PV_VISA = c.payment_PV_VISA,
                                                           payment_Orther_1 = c.payment_Orther_1,
                                                           payment_Orther_2 = c.payment_Orther_2,
                                                           payment_Orther_3 = c.payment_Orther_3,
                                                           payment_Sub_1 = c.payment_Sub_1,
                                                           payment_Sub_2 = c.payment_Sub_2,
                                                           payment_Total = c.payment_Total,
                                                           plan_plan = CommonHelper.Truncate(c.plan_plan, 256),
                                                           Note_note = CommonHelper.Truncate(c.Note_note, 256),
                                                           requirements_learning = c.requirements_learning,
                                                           requirements_financial = c.requirements_financial,
                                                           requirements_accountNumber = c.requirements_accountNumber,
                                                           requirements_income = c.requirements_income,
                                                           requirements_work = c.requirements_work,
                                                           requirements_conditions = c.requirements_conditions,
                                                           requirements_responsibility = c.requirements_responsibility,
                                                           marketing = CommonHelper.Truncate(c.marketing, 128),
                                                           marketing_results = CommonHelper.Truncate(c.marketing_results, 128),
                                                           CustCounselor = c.CustCounselor,
                                                           payment_SK = c.payment_SK,
                                                           payment_Orther_4 = c.payment_Orther_4,
                                                           SourcePetition = c.SourcePetition,
                                                           SourceToNation = c.SourceToNation,
                                                           MimeType = c.MimeType,
                                                           imageUrl = c.imageUrl,
                                                           Addprofile = CommonHelper.ToDate(c.Addprofile),
                                                           AddprofileSchools = CommonHelper.ToDate(c.AddprofileSchools),
                                                           AddSeviceFreeSchools = CommonHelper.ToDate(c.AddSeviceFreeSchools),
                                                           Addhealthcare = CommonHelper.ToDate(c.Addhealthcare),
                                                           AddSeviceFree = CommonHelper.ToDate(c.AddSeviceFree),
                                                           AddI20offer = CommonHelper.ToDate(c.AddI20offer),
                                                           AddCheckI20offer = CommonHelper.ToDate(c.AddCheckI20offer),
                                                           Registrationticket = CommonHelper.ToDate(c.Registrationticket),
                                                           Registrationtaccommodation = CommonHelper.ToDate(c.Registrationtaccommodation),
                                                           Registrationairport = CommonHelper.ToDate(c.Registrationairport),
                                                           TransferSchool = CommonHelper.ToDate(c.TransferSchool)
                                                           #endregion
                                                       };
                m_context.Customers.InsertOnSubmit(item);
                this.UpdateCustomerLastId(c.CutomerTypeId);
            }
            else
            {
                #region CustomerInfo
                item.CustomerID = c.CustomerID;
                item.CustName = CommonHelper.Truncate(c.CustName, 128);
                item.CustCaseWork = caseWord;
                item.CustDate = CommonHelper.ToDate(c.CustDate);
                item.CustHour = c.CustHour;
                item.CustDateOfBirth = c.CustDateOfBirth;
                item.CustPlate = c.CustPlate;
                item.CustParent = c.CustParent;
                item.CustEmail = c.CustEmail;
                item.CustAddres = c.CustAddres;
                item.CustCompany = c.CustCompany;
                item.CustMobile = c.CustMobile;
                item.CustPhone = c.CustPhone;
                item.CustEdu = c.CustEdu;
                item.CustFax = c.CustFax;
                item.CustLangue = c.CustLangue;
                item.CustCareer = c.CustCareer;
                item.isVisa = c.isVisa;
                item.NationalId = c.NationalId;
                item.CustYear = c.CustYear;
                item.VisaNumber = c.VisaNumber;
                item.isTravel = c.isTravel;
                item.TravelNation = c.TravelNation;
                item.TravelNote = CommonHelper.Truncate(c.TravelNote, 128);
                item.CustSource = c.CustSource;
                item.IsStudy = c.IsStudy;
                item.CustNationalId = c.CustNationalId;
                item.CustCity = c.CustCity;
                item.CustState = c.CustState;
                item.CustLevel = c.CustLevel;
                item.CustStady = c.CustStady;
                item.CustSchool = c.CustSchool;
                item.CustRelative = c.CustRelative;
                item.CustRelativeAddre = c.CustRelativeAddre;
                item.CustNote = CommonHelper.Truncate(c.CustNote, 128);
                item.CustFollowUpDate01 = c.CustFollowUpDate01;
                item.CustFollowUpDate02 = c.CustFollowUpDate02;
                item.CustFollowUpDate03 = c.CustFollowUpDate03;
                item.CustNewNex01 = c.CustNewNex01;
                item.CustNewNex02 = c.CustNewNex02;
                item.CustNewNex03 = c.CustNewNex03;
                item.CustIsDate = c.CustIsDate;
                item.CustSignature = c.CustSignature;
                item.studyTravelOther = c.studyTravelOther;
                item.ProDate = CommonHelper.ToDate(c.ProDate);
                item.ProCurator = c.ProCurator;
                item.ProFullName = c.ProFullName;
                item.ProSource = c.ProSource;
                item.ProSchool = c.ProSchool;
                item.ProProgram = c.ProProgram;
                item.ProDateOfAdmission = CommonHelper.ToDate(c.ProDateOfAdmission);
                item.ProscheduledInterviewDate = CommonHelper.ToDate(c.ProscheduledInterviewDate);
                item.ProOther = c.ProOther;
                item.ProBaccalaureate = c.ProBaccalaureate;
                item.ProGraduateIndustry = c.ProGraduateIndustry;
                item.ProGraduateYear = c.ProGraduateYear;
                item.ProWorking = c.ProWorking;
                item.ProLearning = c.ProLearning;
                item.Deleted = false;
                item.UpdateByID = c.UpdateByID;
                item.UpdatedOn = c.UpdatedOn;
                item.CutomerTypeId = c.CutomerTypeId;
                item.ProFinanCapital = c.ProFinanCapital;
                item.ProFinanIndustry = c.ProFinanIndustry;
                item.ProFinanOther = c.ProFinanOther;
                item.ProFinanRental = c.ProFinanRental;
                item.ProFinanShipPapers = c.ProFinanShipPapers;
                item.ProPropertyAccountValue = c.ProPropertyAccountValue;
                item.ProPropertyCar = c.ProPropertyCar;
                item.ProPropertyLand = c.ProPropertyLand;
                item.ProPropertyOther = c.ProPropertyOther;
                item.statusVisa = c.statusVisa;
                item.businesstype = CommonHelper.Truncate(c.businesstype, 128);
                item.busRealEstateInfo = c.busRealEstateInfo;
                item.busRealMonthlyTax = c.busRealMonthlyTax;
                item.busMontlyIncome = c.busMontlyIncome;
                item.busOther = CommonHelper.Truncate(c.busOther, 128);
                item.requirements = CommonHelper.Truncate(c.requirements, 256);
                item.payment_1 = c.payment_1;
                item.payment_2 = c.payment_2;
                item.payment_accountNumber = c.payment_accountNumber;
                item.payment_financial = c.payment_financial;
                item.payment_AN = c.payment_AN;
                item.payment_GD = c.payment_GD;
                item.payment_PV_VISA = c.payment_PV_VISA;
                item.payment_Orther_1 = c.payment_Orther_1;
                item.payment_Orther_2 = c.payment_Orther_2;
                item.payment_Orther_3 = c.payment_Orther_3;
                item.payment_Sub_1 = c.payment_Sub_1;
                item.payment_Sub_2 = c.payment_Sub_2;
                item.payment_Total = c.payment_Total;
                item.plan_plan = CommonHelper.Truncate(c.plan_plan, 256);
                item.Note_note = CommonHelper.Truncate(c.Note_note, 256);
                item.requirements_learning = c.requirements_learning;
                item.requirements_financial = c.requirements_financial;
                item.requirements_accountNumber = c.requirements_accountNumber;
                item.requirements_income = c.requirements_income;
                item.requirements_work = c.requirements_work;
                item.requirements_conditions = c.requirements_conditions;
                item.requirements_responsibility = c.requirements_responsibility;
                item.marketing = CommonHelper.Truncate(c.marketing, 128);
                item.marketing_results = CommonHelper.Truncate(c.marketing_results, 128);
                item.payment_SK = CommonHelper.Truncate(c.payment_SK, 128);
                item.payment_Orther_4 = CommonHelper.Truncate(c.payment_Orther_4, 128);
                item.CustCounselor = c.CustCounselor;
                item.SourcePetition = c.SourcePetition;
                item.SourceToNation = c.SourceToNation;
                if (c.MimeType.Length > 0)
                {
                    item.MimeType = c.MimeType;
                    item.imageUrl = c.imageUrl;
                }
                item.Addprofile = CommonHelper.ToDate(c.Addprofile);
                item.AddprofileSchools = CommonHelper.ToDate(c.AddprofileSchools);
                item.AddSeviceFreeSchools = CommonHelper.ToDate(c.AddSeviceFreeSchools);
                item.Addhealthcare = CommonHelper.ToDate(c.Addhealthcare);
                item.AddSeviceFree = CommonHelper.ToDate(c.AddSeviceFree);
                item.AddI20offer = CommonHelper.ToDate(c.AddI20offer);
                item.AddCheckI20offer = CommonHelper.ToDate(c.AddCheckI20offer);
                item.Registrationticket = CommonHelper.ToDate(c.Registrationticket);
                item.Registrationtaccommodation = CommonHelper.ToDate(c.Registrationtaccommodation);
                item.Registrationairport = CommonHelper.ToDate(c.Registrationairport);
                item.TransferSchool = CommonHelper.ToDate(c.TransferSchool);
                #endregion
            }
            m_context.SubmitChanges();

            return item.CustomerID;
        }

        public int Delete(List<int> List)
        {
            bool flag = false;
            using (var trans = new System.Transactions.TransactionScope())
            {
                m_context.Customers.Where(c => List.Contains(c.CustomerID)).ToList().ForEach(c => c.Deleted = true);
                m_context.SubmitChanges();
                trans.Complete();
                flag = true;
            }
            return flag ? List.Count : 0;
        }

        public PagedList<Customer> GetAllCustomer(int pageSize, int pageIndex)
        {
            var query = from c in m_context.Customers
                        where c.Deleted == false
                        select new Customer
                        {
                            #region
                            CustomerID = c.CustomerID,
                            CustName = c.CustName,
                            CustCaseWork = c.CustCaseWork,
                            CustDate = CommonHelper.Format(c.CustDate),
                            CustHour = c.CustHour,
                            CustDateOfBirth = c.CustDateOfBirth,
                            CustPlate = c.CustPlate,
                            CustParent = c.CustParent,
                            CustEmail = c.CustEmail,
                            CustAddres = c.CustAddres,
                            CustCompany = c.CustCompany,
                            CustMobile = c.CustMobile,
                            CustPhone = c.CustPhone,
                            CustEdu = c.CustEdu,
                            CustFax = c.CustFax,
                            CustLangue = c.CustLangue,
                            CustCareer = c.CustCareer,
                            isVisa = c.isVisa,
                            NationalId = c.NationalId == null ? 0 : c.NationalId.Value,
                            CustYear = c.CustYear,
                            VisaNumber = c.VisaNumber == null ? 0 : c.VisaNumber.Value,
                            isTravel = c.isTravel,
                            TravelNation = c.TravelNation,
                            TravelNote = c.TravelNote,
                            CustSource = c.CustSource,
                            IsStudy = c.IsStudy,
                            CustNationalId = c.CustNationalId == null ? 0 : c.CustNationalId.Value,
                            CustCity = c.CustCity,
                            CustState = c.CustState,
                            CustLevel = c.CustLevel,
                            CustStady = c.CustStady,
                            CustSchool = c.CustSchool,
                            CustRelative = c.CustRelative,
                            CustRelativeAddre = c.CustRelativeAddre,
                            CustNote = c.CustNote,
                            CustFollowUpDate01 = c.CustFollowUpDate01,
                            CustFollowUpDate02 = c.CustFollowUpDate02,
                            CustFollowUpDate03 = c.CustFollowUpDate03,
                            CustNewNex01 = c.CustNewNex01,
                            CustNewNex02 = c.CustNewNex02,
                            CustNewNex03 = c.CustNewNex03,
                            CustIsDate = c.CustIsDate,
                            CustSignature = c.CustSignature == null ? false : c.CustSignature.Value,
                            studyTravelOther = c.studyTravelOther,
                            ProDate = CommonHelper.Format(c.ProDate),
                            ProCurator = c.ProCurator,
                            ProFullName = c.ProFullName,
                            ProSource = c.ProSource,
                            ProSchool = c.ProSchool,
                            ProProgram = c.ProProgram,
                            ProDateOfAdmission = CommonHelper.Format(c.ProDateOfAdmission),
                            ProscheduledInterviewDate = CommonHelper.Format(c.ProscheduledInterviewDate),
                            ProOther = c.ProOther,
                            ProBaccalaureate = c.ProBaccalaureate,
                            ProGraduateIndustry = c.ProGraduateIndustry,
                            ProGraduateYear = c.ProGraduateYear,
                            ProWorking = c.ProWorking,
                            ProLearning = c.ProLearning,
                            Deleted = c.Deleted,
                            UpdateByID = c.UpdateByID,
                            CreateByID = c.CreateByID,
                            CreatedOn = c.CreatedOn,
                            UpdatedOn = c.UpdatedOn,
                            CutomerTypeId = c.CutomerTypeId == null ? 0 : c.CutomerTypeId.Value,
                            ProFinanIndustry = c.ProFinanIndustry,
                            ProFinanCapital = c.ProFinanCapital,
                            ProFinanOther = c.ProFinanOther,
                            ProFinanRental = c.ProFinanRental,
                            ProFinanShipPapers = c.ProFinanShipPapers,
                            ProPropertyAccountValue = c.ProPropertyAccountValue,
                            ProPropertyCar = c.ProPropertyCar,
                            ProPropertyLand = c.ProPropertyLand,
                            ProPropertyOther = c.ProPropertyOther,
                            statusVisa = c.statusVisa,
                            businesstype = c.businesstype,
                            busRealEstateInfo = c.busRealEstateInfo,
                            busRealMonthlyTax = c.busRealMonthlyTax,
                            busMontlyIncome = c.busMontlyIncome,
                            busOther = c.busOther,
                            requirements = c.requirements,
                            payment_1 = c.payment_1,
                            payment_2 = c.payment_2,
                            payment_accountNumber = c.payment_accountNumber,
                            payment_financial = c.payment_financial,
                            payment_AN = c.payment_AN,
                            payment_GD = c.payment_GD,
                            payment_PV_VISA = c.payment_PV_VISA,
                            payment_Orther_1 = c.payment_Orther_1,
                            payment_Orther_2 = c.payment_Orther_2,
                            payment_Orther_3 = c.payment_Orther_3,
                            payment_Sub_1 = c.payment_Sub_1,
                            payment_Sub_2 = c.payment_Sub_2,
                            payment_Total = c.payment_Total,
                            plan_plan = c.plan_plan,
                            Note_note = c.Note_note,
                            requirements_learning = c.requirements_learning,
                            requirements_financial = c.requirements_financial,
                            requirements_accountNumber = c.requirements_accountNumber,
                            requirements_income = c.requirements_income,
                            requirements_work = c.requirements_work,
                            requirements_conditions = c.requirements_conditions,
                            requirements_responsibility = c.requirements_responsibility,
                            marketing = c.marketing,
                            marketing_results = c.marketing_results,
                            CustCounselor = c.CustCounselor,
                            payment_SK = c.payment_SK,
                            payment_Orther_4 = c.payment_Orther_4,
                            SourcePetition = c.SourcePetition,
                            SourceToNation = c.SourceToNation,
                            imageUrl = c.imageUrl,
                            MimeType = c.MimeType
                            #endregion
                        };

            return new PagedList<Customer>(query, pageIndex, pageSize);
        }
        public PagedList<Customer> GetAllCustomer(CustomerSearchResult filter, int pageSize = int.MaxValue, int pageIndex = 0)
        {
            this.SaveCustomerFilter(filter);
            var query = from c in m_context.Customers
                        join o in m_context.Objects on c.CustNationalId equals o.ObjectId into ObjectJoin
                        from o2 in ObjectJoin.DefaultIfEmpty()
                        join o3 in m_context.Objects on c.NationalId equals o3.ObjectId into ObjectJoin2
                        from o4 in ObjectJoin2.DefaultIfEmpty()
                        where c.Deleted == false && (c.CutomerTypeId == filter.CutomerTypeId || filter.CutomerTypeId == 0)
                        && (c.CustDate.Value.Year == filter.CustYear || filter.CustYear == 0)
                        && (c.CustDate.Value.Month == filter.CustMonth || filter.CustMonth == 0)
                        orderby c.CustomerID descending
                        select new Customer
                        {
                            #region
                            CustomerID = c.CustomerID,
                            CustName = c.CustName,
                            CustCaseWork = c.CustCaseWork,
                            CustDate = CommonHelper.Format(c.CustDate),
                            CustHour = c.CustHour ?? "",
                            CustDateOfBirth = c.CustDateOfBirth ?? "",
                            CustPlate = c.CustPlate ?? "",
                            CustParent = c.CustParent ?? "",
                            CustEmail = c.CustEmail ?? "",
                            CustAddres = c.CustAddres ?? "",
                            CustCompany = c.CustCompany ?? "",
                            CustMobile = c.CustMobile ?? "",
                            CustPhone = c.CustPhone ?? "",
                            CustEdu = c.CustEdu ?? "",
                            CustFax = c.CustFax ?? "",
                            CustLangue = c.CustLangue ?? "",
                            CustCareer = c.CustCareer ?? "",
                            isVisa = c.isVisa,
                            NationalId = c.NationalId == null ? 0 : c.NationalId.Value,
                            CustYear = c.CustYear,
                            VisaNumber = c.VisaNumber == null ? 0 : c.VisaNumber.Value,
                            isTravel = c.isTravel,
                            TravelNation = c.TravelNation,
                            TravelNote = c.TravelNote,
                            CustSource = c.CustSource,
                            IsStudy = c.IsStudy,
                            CustNationalId = c.CustNationalId == null ? 0 : c.CustNationalId.Value,
                            CustCity = c.CustCity,
                            CustState = c.CustState,
                            CustLevel = c.CustLevel,
                            CustStady = c.CustStady,
                            CustSchool = c.CustSchool,
                            CustRelative = c.CustRelative,
                            CustRelativeAddre = c.CustRelativeAddre,
                            CustNote = c.CustNote,
                            CustFollowUpDate01 = c.CustFollowUpDate01,
                            CustFollowUpDate02 = c.CustFollowUpDate02,
                            CustFollowUpDate03 = c.CustFollowUpDate03,
                            CustNewNex01 = c.CustNewNex01,
                            CustNewNex02 = c.CustNewNex02,
                            CustNewNex03 = c.CustNewNex03,
                            CustIsDate = c.CustIsDate,
                            CustSignature = c.CustSignature == null ? false : c.CustSignature.Value,
                            studyTravelOther = c.studyTravelOther,
                            ProDate = CommonHelper.Format(c.ProDate),
                            ProCurator = c.ProCurator,
                            ProFullName = c.ProFullName,
                            ProSource = c.ProSource,
                            ProSchool = c.ProSchool,
                            ProProgram = c.ProProgram,
                            ProDateOfAdmission = CommonHelper.Format(c.ProDateOfAdmission),
                            ProscheduledInterviewDate = CommonHelper.Format(c.ProscheduledInterviewDate),
                            ProOther = c.ProOther,
                            ProBaccalaureate = c.ProBaccalaureate,
                            ProGraduateIndustry = c.ProGraduateIndustry,
                            ProGraduateYear = c.ProGraduateYear,
                            ProWorking = c.ProWorking,
                            ProLearning = c.ProLearning,
                            Deleted = c.Deleted,
                            UpdateByID = c.UpdateByID,
                            CreateByID = c.CreateByID,
                            CreatedOn = c.CreatedOn,
                            UpdatedOn = c.UpdatedOn,
                            CutomerTypeId = c.CutomerTypeId == null ? 0 : c.CutomerTypeId.Value,
                            ProFinanIndustry = c.ProFinanIndustry,
                            ProFinanCapital = c.ProFinanCapital,
                            ProFinanOther = c.ProFinanOther,
                            ProFinanRental = c.ProFinanRental,
                            ProFinanShipPapers = c.ProFinanShipPapers,
                            ProPropertyAccountValue = c.ProPropertyAccountValue,
                            ProPropertyCar = c.ProPropertyCar,
                            ProPropertyLand = c.ProPropertyLand,
                            ProPropertyOther = c.ProPropertyOther,
                            statusVisa = c.statusVisa,
                            businesstype = c.businesstype,
                            busRealEstateInfo = c.busRealEstateInfo,
                            busRealMonthlyTax = c.busRealMonthlyTax,
                            busMontlyIncome = c.busMontlyIncome,
                            busOther = c.busOther,
                            requirements = c.requirements,
                            payment_1 = c.payment_1,
                            payment_2 = c.payment_2,
                            payment_accountNumber = c.payment_accountNumber,
                            payment_financial = c.payment_financial,
                            payment_AN = c.payment_AN,
                            payment_GD = c.payment_GD,
                            payment_PV_VISA = c.payment_PV_VISA,
                            payment_Orther_1 = c.payment_Orther_1,
                            payment_Orther_2 = c.payment_Orther_2,
                            payment_Orther_3 = c.payment_Orther_3,
                            payment_Sub_1 = c.payment_Sub_1,
                            payment_Sub_2 = c.payment_Sub_2,
                            payment_Total = c.payment_Total,
                            plan_plan = c.plan_plan,
                            Note_note = c.Note_note,
                            requirements_learning = c.requirements_learning,
                            requirements_financial = c.requirements_financial,
                            requirements_accountNumber = c.requirements_accountNumber,
                            requirements_income = c.requirements_income,
                            requirements_work = c.requirements_work,
                            requirements_conditions = c.requirements_conditions,
                            requirements_responsibility = c.requirements_responsibility,
                            marketing = c.marketing,
                            marketing_results = c.marketing_results,
                            CustCounselor = c.CustCounselor,
                            payment_SK = c.payment_SK,
                            payment_Orther_4 = c.payment_Orther_4,
                            SourcePetition = c.SourcePetition,
                            SourceToNation = c.SourceToNation,
                            CustNationalName = o2.ObjectName ?? "N/A",
                            NationalName = o4.ObjectName ?? "N/A",
                            imageUrl = c.imageUrl,
                            MimeType = c.MimeType ?? "",
                            Addprofile = CommonHelper.Format(c.Addprofile),
                            AddprofileSchools = CommonHelper.Format(c.AddprofileSchools),
                            AddSeviceFreeSchools = CommonHelper.Format(c.AddSeviceFreeSchools),
                            Addhealthcare = CommonHelper.Format(c.Addhealthcare),
                            AddSeviceFree = CommonHelper.Format(c.AddSeviceFree),
                            AddI20offer = CommonHelper.Format(c.AddI20offer),
                            AddCheckI20offer = CommonHelper.Format(c.AddCheckI20offer),
                            Registrationticket = CommonHelper.Format(c.Registrationticket),
                            Registrationtaccommodation = CommonHelper.Format(c.Registrationtaccommodation),
                            Registrationairport = CommonHelper.Format(c.Registrationairport),
                            TransferSchool = CommonHelper.Format(c.TransferSchool)
                            #endregion
                        };
            if (filter.CustNationalId > 0)
            {
                query = query.Where(c => c.CustNationalId == filter.CustNationalId);
            }
            if (!CommonHelper.IsBlank(filter.CustName))
            {
                query = query.Where(c => c.CustName.ToLower().Contains(filter.CustName.ToLower()));
            }
            if (!CommonHelper.IsBlank(filter.CustCaseWork))
            {
                query = query.Where(c => c.CustCaseWork.ToLower().Contains(filter.CustCaseWork.ToLower()));
            }
            if (!CommonHelper.IsBlank(filter.CustMobile))
            {
                query = query.Where(c => c.CustMobile.ToLower().Contains(filter.CustMobile.ToLower()));
            }
            if (!CommonHelper.IsBlank(filter.CustParent))
            {
                query = query.Where(c => c.CustParent.ToLower().Contains(filter.CustParent.ToLower()));
            }
            if (!CommonHelper.IsBlank(filter.CustHour))
            {
                query = query.Where(c => c.CustHour.ToLower().Contains(filter.CustHour.ToLower()));
            }

            if (!CommonHelper.IsBlank(filter.CustCounselor))
            {
                query = query.Where(c => c.CustCounselor.ToLower().Contains(filter.CustCounselor.ToLower()));
            }
            if (filter.statusVisa != 6)
            {
                query = query.Where(c => c.statusVisa == filter.statusVisa);
            }
            if (filter.IsStudy != 4)
            {
                query = query.Where(c => c.IsStudy == filter.IsStudy);
            }
            if (!CommonHelper.IsBlank(filter.CustSchool))
            {
                query = query.Where(c => c.CustSchool.ToLower().Contains(filter.CustSchool.ToLower()));
            }

            if (!CommonHelper.IsBlank(filter.ProCurator))
            {
                query = query.Where(c => c.ProCurator.ToLower().Contains(filter.ProCurator.ToLower()));
            }
            if (!filter.CustYearOfBirth.Equals("0"))
            {
                query = query.Where(c => c.CustDateOfBirth.ToLower().Contains(filter.CustYearOfBirth.ToLower()));
            }
            if (!filter.CustMonthOfBirth.Equals("0"))
            {
                query = query.Where(c => c.CustDateOfBirth.ToLower().Contains(filter.CustMonthOfBirth.ToLower()));
            }

            return new PagedList<Customer>(query, pageIndex, pageSize);
        }
        public Customer GetCustomerById(int customerId)
        {
            var query = from c in m_context.Customers
                        join o in m_context.Objects on c.CustNationalId equals o.ObjectId into ObjectJoin
                        from o2 in ObjectJoin.DefaultIfEmpty()
                        where c.CustomerID == customerId //&& o2.ObjectTypeId == 1
                        select new Customer
                                            {
                                                #region
                                                CustomerID = c.CustomerID,
                                                CustName = c.CustName,
                                                CustCaseWork = c.CustCaseWork,
                                                CustDate = CommonHelper.Format(c.CustDate),
                                                CustHour = c.CustHour ?? "",
                                                CustDateOfBirth = c.CustDateOfBirth ?? "",
                                                CustPlate = c.CustPlate ?? "",
                                                CustParent = c.CustParent ?? "",
                                                CustEmail = c.CustEmail ?? "",
                                                CustAddres = c.CustAddres ?? "",
                                                CustCompany = c.CustCompany ?? "",
                                                CustMobile = c.CustMobile ?? "",
                                                CustPhone = c.CustPhone ?? "",
                                                CustEdu = c.CustEdu ?? "",
                                                CustFax = c.CustFax ?? "",
                                                CustLangue = c.CustLangue ?? "",
                                                CustCareer = c.CustCareer ?? "",
                                                isVisa = c.isVisa,
                                                NationalId = c.NationalId == null ? 0 : c.NationalId.Value,
                                                CustYear = c.CustYear,
                                                VisaNumber = c.VisaNumber == null ? 0 : c.VisaNumber.Value,
                                                isTravel = c.isTravel,
                                                TravelNation = c.TravelNation ?? "",
                                                TravelNote = c.TravelNote ?? "",
                                                CustSource = c.CustSource ?? "",
                                                IsStudy = c.IsStudy,
                                                CustNationalId = c.CustNationalId == null ? 0 : c.CustNationalId.Value,
                                                CustNationalName = o2.ObjectName ?? "",
                                                CustCity = c.CustCity ?? "",
                                                CustState = c.CustState ?? "",
                                                CustLevel = c.CustLevel ?? "",
                                                CustStady = c.CustStady ?? "",
                                                CustSchool = c.CustSchool ?? "",
                                                CustRelative = c.CustRelative ?? "",
                                                CustRelativeAddre = c.CustRelativeAddre ?? "",
                                                CustNote = c.CustNote ?? "",
                                                CustFollowUpDate01 = c.CustFollowUpDate01 ?? ";",
                                                CustFollowUpDate02 = c.CustFollowUpDate02 ?? ";",
                                                CustFollowUpDate03 = c.CustFollowUpDate03 ?? ";",
                                                CustNewNex01 = c.CustNewNex01 ?? ";",
                                                CustNewNex02 = c.CustNewNex02 ?? ";",
                                                CustNewNex03 = c.CustNewNex03 ?? ";",
                                                CustIsDate = c.CustIsDate,
                                                CustSignature = c.CustSignature == null ? false : c.CustSignature.Value,
                                                studyTravelOther = c.studyTravelOther,
                                                ProDate = CommonHelper.Format(c.ProDate),
                                                ProCurator = c.ProCurator ?? "",
                                                ProFullName = c.ProFullName ?? "",
                                                ProSource = c.ProSource ?? "",
                                                ProSchool = c.ProSchool ?? "",
                                                ProProgram = c.ProProgram ?? "",
                                                ProDateOfAdmission = CommonHelper.Format(c.ProDateOfAdmission),
                                                ProscheduledInterviewDate = CommonHelper.Format(c.ProscheduledInterviewDate),
                                                ProOther = c.ProOther ?? "",
                                                ProBaccalaureate = c.ProBaccalaureate,
                                                ProGraduateIndustry = c.ProGraduateIndustry ?? "",
                                                ProGraduateYear = c.ProGraduateYear,
                                                ProWorking = c.ProWorking ?? "",
                                                ProLearning = c.ProLearning ?? "",
                                                Deleted = c.Deleted,
                                                UpdateByID = c.UpdateByID,
                                                CreateByID = c.CreateByID,
                                                CreatedOn = c.CreatedOn,
                                                UpdatedOn = c.UpdatedOn,
                                                CutomerTypeId = c.CutomerTypeId == null ? 0 : c.CutomerTypeId.Value,
                                                ProFinanIndustry = c.ProFinanIndustry,
                                                ProFinanCapital = c.ProFinanCapital,
                                                ProFinanOther = c.ProFinanOther,
                                                ProFinanRental = c.ProFinanRental,
                                                ProFinanShipPapers = c.ProFinanShipPapers,
                                                ProPropertyAccountValue = c.ProPropertyAccountValue,
                                                ProPropertyCar = c.ProPropertyCar,
                                                ProPropertyLand = c.ProPropertyLand,
                                                ProPropertyOther = c.ProPropertyOther,
                                                statusVisa = c.statusVisa,
                                                businesstype = c.businesstype,
                                                busRealEstateInfo = c.busRealEstateInfo,
                                                busRealMonthlyTax = c.busRealMonthlyTax,
                                                busMontlyIncome = c.busMontlyIncome,
                                                busOther = c.busOther,
                                                requirements = c.requirements,
                                                payment_1 = c.payment_1,
                                                payment_2 = c.payment_2,
                                                payment_accountNumber = c.payment_accountNumber,
                                                payment_financial = c.payment_financial,
                                                payment_AN = c.payment_AN,
                                                payment_GD = c.payment_GD,
                                                payment_PV_VISA = c.payment_PV_VISA,
                                                payment_Orther_1 = c.payment_Orther_1,
                                                payment_Orther_2 = c.payment_Orther_2,
                                                payment_Orther_3 = c.payment_Orther_3,
                                                payment_Sub_1 = c.payment_Sub_1,
                                                payment_Sub_2 = c.payment_Sub_2,
                                                payment_Total = c.payment_Total,
                                                plan_plan = c.plan_plan,
                                                Note_note = c.Note_note,
                                                requirements_learning = c.requirements_learning,
                                                requirements_financial = c.requirements_financial,
                                                requirements_accountNumber = c.requirements_accountNumber,
                                                requirements_income = c.requirements_income,
                                                requirements_work = c.requirements_work,
                                                requirements_conditions = c.requirements_conditions,
                                                requirements_responsibility = c.requirements_responsibility,
                                                marketing = c.marketing,
                                                marketing_results = c.marketing_results,
                                                CustCounselor = c.CustCounselor,
                                                payment_SK = c.payment_SK,
                                                payment_Orther_4 = c.payment_Orther_4,
                                                SourcePetition = c.SourcePetition,
                                                SourceToNation = c.SourceToNation,
                                                imageUrl = c.imageUrl,
                                                MimeType = c.MimeType ?? "",
                                                Addprofile = CommonHelper.Format(c.Addprofile),
                                                AddprofileSchools = CommonHelper.Format(c.AddprofileSchools),
                                                AddSeviceFreeSchools = CommonHelper.Format(c.AddSeviceFreeSchools),
                                                Addhealthcare = CommonHelper.Format(c.Addhealthcare),
                                                AddSeviceFree = CommonHelper.Format(c.AddSeviceFree),
                                                AddI20offer = CommonHelper.Format(c.AddI20offer),
                                                AddCheckI20offer = CommonHelper.Format(c.AddCheckI20offer),
                                                Registrationticket = CommonHelper.Format(c.Registrationticket),
                                                Registrationtaccommodation = CommonHelper.Format(c.Registrationtaccommodation),
                                                Registrationairport = CommonHelper.Format(c.Registrationairport),
                                                TransferSchool = CommonHelper.Format(c.TransferSchool)
                                                #endregion
                                            };
            return query.FirstOrDefault();
        }
        public Customer GetCustomerByName(string name = "")
        {
            var query = from c in m_context.Customers
                        where c.CustName.ToUpper() == name.ToUpper()
                        select new Customer
                        {
                            #region
                            CustomerID = c.CustomerID,
                            CustName = c.CustName,
                            CustCaseWork = c.CustCaseWork,
                            CustDate = CommonHelper.Format(c.CustDate),
                            CustHour = c.CustHour ?? "",
                            CustDateOfBirth = c.CustDateOfBirth ?? "",
                            CustPlate = c.CustPlate ?? "",
                            CustParent = c.CustParent ?? "",
                            CustEmail = c.CustEmail ?? "",
                            CustAddres = c.CustAddres ?? "",
                            CustCompany = c.CustCompany ?? "",
                            CustMobile = c.CustMobile ?? "",
                            CustPhone = c.CustPhone ?? "",
                            CustEdu = c.CustEdu ?? "",
                            CustFax = c.CustFax ?? "",
                            CustLangue = c.CustLangue ?? "",
                            CustCareer = c.CustCareer ?? "",
                            isVisa = c.isVisa,
                            NationalId = c.NationalId == null ? 0 : c.NationalId.Value,
                            CustYear = c.CustYear,
                            VisaNumber = c.VisaNumber == null ? 0 : c.VisaNumber.Value,
                            isTravel = c.isTravel,
                            TravelNation = c.TravelNation ?? "",
                            TravelNote = c.TravelNote ?? "",
                            CustSource = c.CustSource ?? "",
                            IsStudy = c.IsStudy,
                            CustNationalId = c.CustNationalId == null ? 0 : c.CustNationalId.Value,
                            CustCity = c.CustCity ?? "",
                            CustState = c.CustState ?? "",
                            CustLevel = c.CustLevel ?? "",
                            CustStady = c.CustStady ?? "",
                            CustSchool = c.CustSchool ?? "",
                            CustRelative = c.CustRelative ?? "",
                            CustRelativeAddre = c.CustRelativeAddre ?? "",
                            CustNote = c.CustNote ?? "",
                            CustFollowUpDate01 = c.CustFollowUpDate01 ?? ";",
                            CustFollowUpDate02 = c.CustFollowUpDate02 ?? ";",
                            CustFollowUpDate03 = c.CustFollowUpDate03 ?? ";",
                            CustNewNex01 = c.CustNewNex01 ?? ";",
                            CustNewNex02 = c.CustNewNex02 ?? ";",
                            CustNewNex03 = c.CustNewNex03 ?? ";",
                            CustIsDate = c.CustIsDate,
                            CustSignature = c.CustSignature == null ? false : c.CustSignature.Value,
                            studyTravelOther = c.studyTravelOther,
                            ProDate = CommonHelper.Format(c.ProDate),
                            ProCurator = c.ProCurator ?? "",
                            ProFullName = c.ProFullName ?? "",
                            ProSource = c.ProSource ?? "",
                            ProSchool = c.ProSchool ?? "",
                            ProProgram = c.ProProgram ?? "",
                            ProDateOfAdmission = CommonHelper.Format(c.ProDateOfAdmission),
                            ProscheduledInterviewDate = CommonHelper.Format(c.ProscheduledInterviewDate),
                            ProOther = c.ProOther ?? "",
                            ProBaccalaureate = c.ProBaccalaureate,
                            ProGraduateIndustry = c.ProGraduateIndustry ?? "",
                            ProGraduateYear = c.ProGraduateYear,
                            ProWorking = c.ProWorking ?? "",
                            ProLearning = c.ProLearning ?? "",
                            Deleted = c.Deleted,
                            UpdateByID = c.UpdateByID,
                            CreateByID = c.CreateByID,
                            CreatedOn = c.CreatedOn,
                            UpdatedOn = c.UpdatedOn,
                            CutomerTypeId = c.CutomerTypeId == null ? 0 : c.CutomerTypeId.Value,
                            ProFinanIndustry = c.ProFinanIndustry,
                            ProFinanCapital = c.ProFinanCapital,
                            ProFinanOther = c.ProFinanOther,
                            ProFinanRental = c.ProFinanRental,
                            ProFinanShipPapers = c.ProFinanShipPapers,
                            ProPropertyAccountValue = c.ProPropertyAccountValue,
                            ProPropertyCar = c.ProPropertyCar,
                            ProPropertyLand = c.ProPropertyLand,
                            ProPropertyOther = c.ProPropertyOther,
                            statusVisa = c.statusVisa,
                            businesstype = c.businesstype,
                            busRealEstateInfo = c.busRealEstateInfo,
                            busRealMonthlyTax = c.busRealMonthlyTax,
                            busMontlyIncome = c.busMontlyIncome,
                            busOther = c.busOther,
                            requirements = c.requirements,
                            payment_1 = c.payment_1,
                            payment_2 = c.payment_2,
                            payment_accountNumber = c.payment_accountNumber,
                            payment_financial = c.payment_financial,
                            payment_AN = c.payment_AN,
                            payment_GD = c.payment_GD,
                            payment_PV_VISA = c.payment_PV_VISA,
                            payment_Orther_1 = c.payment_Orther_1,
                            payment_Orther_2 = c.payment_Orther_2,
                            payment_Orther_3 = c.payment_Orther_3,
                            payment_Sub_1 = c.payment_Sub_1,
                            payment_Sub_2 = c.payment_Sub_2,
                            payment_Total = c.payment_Total,
                            plan_plan = c.plan_plan,
                            Note_note = c.Note_note,
                            requirements_learning = c.requirements_learning,
                            requirements_financial = c.requirements_financial,
                            requirements_accountNumber = c.requirements_accountNumber,
                            requirements_income = c.requirements_income,
                            requirements_work = c.requirements_work,
                            requirements_conditions = c.requirements_conditions,
                            requirements_responsibility = c.requirements_responsibility,
                            marketing = c.marketing,
                            marketing_results = c.marketing_results,
                            CustCounselor = c.CustCounselor,
                            payment_SK = c.payment_SK,
                            payment_Orther_4 = c.payment_Orther_4,
                            SourcePetition = c.SourcePetition,
                            SourceToNation = c.SourceToNation
                            #endregion
                        };
            return query.FirstOrDefault();
        }
        #endregion

        #region Profile
        public int SaveProfile(profile p)
        {
            if (p.CustomerID == 0)
                throw new ArgumentNullException("SaveProfile");

            var item = (from pro in m_context.Profiles
                        where pro.ProfileID == p.ProfileID
                        select pro).FirstOrDefault();
            if (CommonHelper.IsNull(item))
            {
                item = new BusinessLogic.Data.Profile
                {
                    ProfileID = p.ProfileID,
                    CustomerID = p.CustomerID,
                    ObjectID = p.ObjectID,
                    OriginalCopy = p.OriginalCopy,
                    duplicate = p.duplicate,
                    OnRequest = CommonHelper.ToDate(p.OnRequest),
                    DateSubmitted = CommonHelper.ToDate(p.DateSubmitted),
                    Note = p.Note,
                    UpdateByID = p.UpdateByID,
                    CreateByID = p.CreateByID,
                    CreatedOn = p.CreatedOn,
                    UpdatedOn = p.UpdatedOn
                };
                m_context.Profiles.InsertOnSubmit(item);
                m_context.SubmitChanges();
            }
            else
            {
                item.ProfileID = p.ProfileID;
                item.CustomerID = p.CustomerID;
                item.ObjectID = p.ObjectID;
                item.OriginalCopy = p.OriginalCopy;
                item.duplicate = p.duplicate;
                item.OnRequest = CommonHelper.ToDate(p.OnRequest);
                item.DateSubmitted = CommonHelper.ToDate(p.DateSubmitted);
                item.Note = p.Note;
                item.UpdateByID = p.UpdateByID;
                item.CreateByID = p.CreateByID;
                item.CreatedOn = p.CreatedOn;
                item.UpdatedOn = p.UpdatedOn;
                m_context.SubmitChanges();
            }
            return item.ProfileID;
        }
        public int DeleteProfile(List<int> ProfileIDColection)
        {

            bool flag = false;
            using (var trans = new System.Transactions.TransactionScope())
            {
                var query = from p in m_context.Profiles
                            where ProfileIDColection.Contains(p.ProfileID)
                            select p;
                m_context.Profiles.DeleteAllOnSubmit(query);
                m_context.SubmitChanges();
                trans.Complete();
                flag = true;
            }
            return flag ? ProfileIDColection.Count : 0;
        }

        public List<profile> GetAllProfileByCustomerID(int customerId, int ObjectID = 0)
        {
            var query = from p in m_context.Profiles
                        join o in m_context.Objects on p.ObjectID equals o.ObjectId into ObjectJoin
                        from o2 in ObjectJoin.DefaultIfEmpty()
                        where p.CustomerID == customerId && o2.ObjectTypeId == ObjectID
                        select new profile
                        {
                            ProfileID = p.ProfileID,
                            CustomerID = p.CustomerID,
                            ObjectID = p.ObjectID,
                            ObjectName = o2.ObjectName,
                            OriginalCopy = p.OriginalCopy,
                            duplicate = p.duplicate,
                            OnRequest = CommonHelper.Format(p.OnRequest),
                            DateSubmitted = CommonHelper.Format(p.DateSubmitted),
                            Note = p.Note,
                            UpdateByID = p.UpdateByID,
                            CreateByID = p.CreateByID,
                            CreatedOn = p.CreatedOn,
                            UpdatedOn = p.UpdatedOn,
                        };
            return query.ToList();
        }
        #endregion

        #region ProfileFinan
        public int SaveProfileFinan(ProfileFinan pr)
        {
            if (pr.CustomerID == 0)
                throw new ArgumentNullException("SaveProfileFinan");

            var item = (from p in m_context.ProfileFinans
                        where p.ProfileFinanID == pr.ProfileFinanID
                        select p).FirstOrDefault();
            if (CommonHelper.IsNull(item))
            {
                item = new BusinessLogic.Data.ProfileFinan
                {
                    ProfileFinanID = pr.ProfileFinanID,
                    CustomerID = pr.CustomerID,
                    PaperRequest = pr.PaperRequest,
                    Content = pr.Content,
                    OnDate = CommonHelper.ToDate(pr.OnDate),
                    WHoDo = pr.WHoDo,
                    Postage = pr.Postage,
                    ProComplete = pr.ProComplete,
                    UpdateByID = pr.UpdateByID,
                    CreateByID = pr.CreateByID,
                    CreatedOn = pr.CreatedOn,
                    UpdatedOn = pr.UpdatedOn
                };
                m_context.ProfileFinans.InsertOnSubmit(item);
                m_context.SubmitChanges();
            }
            else
            {
                item.ProfileFinanID = pr.ProfileFinanID;
                item.CustomerID = pr.CustomerID;
                item.PaperRequest = pr.PaperRequest;
                item.Content = pr.Content;
                item.OnDate = CommonHelper.ToDate(pr.OnDate);
                item.WHoDo = pr.WHoDo;
                item.Postage = pr.Postage;
                item.ProComplete = pr.ProComplete;
                item.UpdateByID = pr.UpdateByID;
                item.CreateByID = pr.CreateByID;
                item.CreatedOn = pr.CreatedOn;
                item.UpdatedOn = pr.UpdatedOn;
                m_context.SubmitChanges();
            }
            return item.ProfileFinanID;
        }

        public int DeleteProfileFinan(List<int> profileFinanColection)
        {
            bool flag = false;
            using (var trans = new System.Transactions.TransactionScope())
            {
                var query = from p in m_context.ProfileFinans
                            where profileFinanColection.Contains(p.ProfileFinanID)
                            select p;
                m_context.ProfileFinans.DeleteAllOnSubmit(query);
                m_context.SubmitChanges();
                trans.Complete();
                flag = true;
            }
            return flag ? profileFinanColection.Count : 0;
        }

        public List<ProfileFinan> GetAllByCustomerId(int customerId)
        {
            var query = from pr in m_context.ProfileFinans
                        where pr.CustomerID == customerId
                        select new ProfileFinan
                        {
                            ProfileFinanID = pr.ProfileFinanID,
                            CustomerID = pr.CustomerID,
                            PaperRequest = pr.PaperRequest,
                            Content = pr.Content,
                            OnDate = CommonHelper.Format(pr.OnDate),
                            WHoDo = pr.WHoDo,
                            Postage = pr.Postage,
                            ProComplete = pr.ProComplete,
                            UpdateByID = pr.UpdateByID,
                            CreateByID = pr.CreateByID,
                            CreatedOn = pr.CreatedOn,
                            UpdatedOn = pr.UpdatedOn
                        };
            return query.ToList();
        }
        #endregion

        #region FeesSchedule
        public int SaveFeesSchedule(FeesSchedule f)
        {
            if (f.CustomerID == 0)
                throw new ArgumentNullException("SaveFeesSchedule");
            var item = (from fs in m_context.FeesSchedules
                        where fs.FeesScheduleID == f.FeesScheduleID
                        select fs).FirstOrDefault();
            if (CommonHelper.IsNull(item))
            {
                item = new BusinessLogic.Data.FeesSchedule
                {
                    FeesScheduleID = f.FeesScheduleID,
                    CustomerID = f.CustomerID,
                    FeesTypeID = f.FeesTypeID,
                    Courses = f.Courses,
                    DateSubmitted = f.DateSubmitted,
                    AmountUSD = f.AmountUSD,
                    AmountVND = f.AmountVND,
                    HaveToPayUSD = f.HaveToPayUSD,
                    HaveToPayVND = f.HaveToPayVND,
                    UpdateByID = f.UpdateByID,
                    CreateByID = f.CreateByID,
                    CreatedOn = f.CreatedOn,
                    UpdatedOn = f.UpdatedOn
                };
                m_context.FeesSchedules.InsertOnSubmit(item);
                m_context.SubmitChanges();
            }
            else
            {

                item.FeesScheduleID = f.FeesScheduleID;
                item.CustomerID = f.CustomerID;
                item.FeesTypeID = f.FeesTypeID;
                item.Courses = f.Courses;
                item.AmountUSD = f.AmountUSD;
                item.AmountVND = f.AmountVND;
                item.HaveToPayUSD = f.HaveToPayUSD;
                item.HaveToPayVND = f.HaveToPayVND;
                item.DateSubmitted = f.DateSubmitted;
                item.UpdateByID = f.UpdateByID;
                item.CreateByID = f.CreateByID;
                item.CreatedOn = f.CreatedOn;
                item.UpdatedOn = f.UpdatedOn;
                m_context.SubmitChanges();
            }
            return item.FeesScheduleID;
        }

        public int DeleteFeesSchedule(List<int> feesScheduleColection)
        {
            bool flag = false;
            using (var trans = new System.Transactions.TransactionScope())
            {
                var query = from p in m_context.FeesSchedules
                            where feesScheduleColection.Contains(p.FeesScheduleID)
                            select p;
                m_context.FeesSchedules.DeleteAllOnSubmit(query);
                m_context.SubmitChanges();
                trans.Complete();
                flag = true;
            }
            return flag ? feesScheduleColection.Count : 0;
        }

        public List<FeesSchedule> GetAllFeesScheduleByCustomerId(int customerId)
        {
            var query = from f in m_context.FeesSchedules
                        join o in m_context.Objects on f.FeesTypeID equals o.ObjectId into ObjectJoin
                        join o3 in m_context.Objects on f.Courses equals o3.ObjectId into ObjCousejoin
                        from o2 in ObjectJoin.DefaultIfEmpty()
                        from o4 in ObjCousejoin.DefaultIfEmpty()
                        where f.CustomerID == customerId
                        select new FeesSchedule
                        {
                            FeesScheduleID = f.FeesScheduleID,
                            CustomerID = f.CustomerID,
                            FeesTypeID = f.FeesTypeID,
                            FessName = o2.ObjectName ?? "N/A",
                            Courses = f.Courses,
                            CoursName = o4.ObjectName ?? "N/A",
                            DateSubmitted = f.DateSubmitted ?? "",
                            AmountUSD = f.AmountUSD,
                            AmountVND = f.AmountVND,
                            HaveToPayUSD = f.HaveToPayUSD,
                            HaveToPayVND = f.HaveToPayVND,
                            UpdateByID = f.UpdateByID,
                            CreateByID = f.CreateByID,
                            CreatedOn = f.CreatedOn,
                            UpdatedOn = f.UpdatedOn
                        };
            return query.ToList();
        }
        #endregion
        public Payroll.BusinessLogic.Data.Object GetNameObject(int id)
        {
            var query = from o in m_context.Objects
                        where o.ObjectId == id
                        select new Payroll.BusinessLogic.Data.Object
                        {
                            ObjectId = o.ObjectId,
                            ObjectName = o.ObjectName,
                            ObjectTypeId = o.ObjectTypeId
                        };
            return query.FirstOrDefault();
        }
        #region ProfileProperty
        public int SaveProfileProperty(ProfileProperty pr)
        {
            if (pr.CustomerID == 0)
                throw new ArgumentNullException("SaveProfileProperty");
            var item = (from p in m_context.ProfileProperties
                        where p.ProfilePropertyID == pr.ProfilePropertyID
                        select p).FirstOrDefault();
            if (CommonHelper.IsNull(item))
            {
                item = new BusinessLogic.Data.ProfileProperty
                {
                    ProfilePropertyID = pr.ProfilePropertyID,
                    CustomerID = pr.CustomerID,
                    PaperRequest = pr.PaperRequest,
                    OnRequest = CommonHelper.ToDate(pr.OnRequest),
                    DateSubmitted = CommonHelper.ToDate(pr.DateSubmitted),
                    ProTo = pr.ProTo,
                    Postage = pr.Postage,
                    Note = CommonHelper.Truncate(pr.Note, 256),
                    ProComplete = pr.ProComplete,
                    UpdateByID = pr.UpdateByID,
                    CreateByID = pr.CreateByID,
                    CreatedOn = pr.CreatedOn,
                    UpdatedOn = pr.UpdatedOn,
                    fromdate = pr.fromdate,
                    todate = pr.todate
                };
                m_context.ProfileProperties.InsertOnSubmit(item);
                m_context.SubmitChanges();
            }
            else
            {
                item.ProfilePropertyID = pr.ProfilePropertyID;
                item.CustomerID = pr.CustomerID;
                item.PaperRequest = pr.PaperRequest;
                item.OnRequest = CommonHelper.ToDate(pr.OnRequest);
                item.DateSubmitted = CommonHelper.ToDate(pr.DateSubmitted);
                item.ProTo = pr.ProTo;
                item.Postage = pr.Postage;
                item.Note = CommonHelper.Truncate(pr.Note, 256);
                item.ProComplete = pr.ProComplete;
                item.UpdateByID = pr.UpdateByID;
                item.CreateByID = pr.CreateByID;
                item.CreatedOn = pr.CreatedOn;
                item.UpdatedOn = pr.UpdatedOn;
                item.fromdate = pr.fromdate;
                item.todate = pr.todate;
                m_context.SubmitChanges();
            }
            return item.ProfilePropertyID;
        }

        public int DeleteProfileProperty(List<int> profilePropertyColection)
        {
            bool flag = false;
            using (var trans = new System.Transactions.TransactionScope())
            {
                var query = from p in m_context.ProfileProperties
                            where profilePropertyColection.Contains(p.ProfilePropertyID)
                            select p;
                m_context.ProfileProperties.DeleteAllOnSubmit(query);
                m_context.SubmitChanges();
                trans.Complete();
                flag = true;
            }
            return flag ? profilePropertyColection.Count : 0;
        }

        public List<ProfileProperty> GetAllProfilePropertyByCustomerId(int customerId)
        {
            var query = from p in m_context.ProfileProperties
                        where p.CustomerID == customerId
                        select new ProfileProperty
                        {
                            ProfilePropertyID = p.ProfilePropertyID,
                            CustomerID = p.CustomerID,
                            PaperRequest = p.PaperRequest ?? "",
                            OnRequest = CommonHelper.Format(p.OnRequest),
                            DateSubmitted = CommonHelper.Format(p.DateSubmitted),
                            ProTo = p.ProTo ?? "",
                            Postage = p.Postage,
                            Note = p.Note ?? "",
                            ProComplete = p.ProComplete ?? "",
                            UpdateByID = p.UpdateByID,
                            CreateByID = p.CreateByID,
                            CreatedOn = p.CreatedOn,
                            UpdatedOn = p.UpdatedOn,
                            fromdate = p.fromdate ?? "",
                            todate = p.todate ?? ""
                        };
            return query.ToList();
        }
        #endregion

        public Customer Save(Customer c, List<profile> ListProfile, List<ProfileProperty> ListProfileProperty, List<ProfileFinan> ListProfileFinan, List<FeesSchedule> ListFeesSchedule, List<Relationships> ListRelation)
        {
            using (var trans = new System.Transactions.TransactionScope())
            {
                int customerId = this.Save(c);
                foreach (var profile in ListProfile)
                {
                    profile.CustomerID = customerId;
                    this.SaveProfile(profile);
                }
                foreach (var profile in ListProfileProperty)
                {
                    profile.CustomerID = customerId;
                    this.SaveProfileProperty(profile);
                }
                foreach (var profile in ListProfileFinan)
                {
                    profile.CustomerID = customerId;
                    this.SaveProfileFinan(profile);
                }
                foreach (var profile in ListFeesSchedule)
                {
                    profile.CustomerID = customerId;
                    this.SaveFeesSchedule(profile);
                }
                this.SaveRelationship(ListRelation, customerId);
                trans.Complete();
                c.CustomerID = customerId;
            }
            return c;
        }


        public List<Objects> GetObjectById(int ObjectTypeId)
        {
            var query = from o in m_context.Objects
                        where o.ObjectTypeId == ObjectTypeId
                        orderby o.Order ascending
                        select new Objects
                        {
                            ObjectId = o.ObjectId,
                            ObjectName = o.ObjectName
                        };
            return query.ToList();
        }


        public string GetCaseWork(int customerTypeId)
        {
            var customertype = (from c in m_context.CutomerTypes
                                where c.CutomerTypeId == customerTypeId
                                orderby c.LastId descending
                                select c).FirstOrDefault();
            if (!CommonHelper.IsNull(customertype))
            {
                return customertype.pre + CommonHelper.ToString(customertype.LastId + 1);
            }
            throw new NotImplementedException();
        }
        private void UpdateCustomerLastId(int customerTypeId)
        {
            var item = (from c in m_context.CutomerTypes
                        where c.CutomerTypeId == customerTypeId
                        orderby c.LastId descending
                        select c).FirstOrDefault();
            if (!CommonHelper.IsNull(item))
            {
                item.LastId = item.LastId + 1;
                m_context.SubmitChanges();
            }
        }

        public List<CutomerType> GetCustomerType(string customerType = "")
        {
            if (string.IsNullOrEmpty(customerType))
                customerType = null;
            var query = from c in m_context.CutomerTypes
                        where c.delete == false && (c.CutomerTypeName.Contains(customerType) || customerType == null)
                        orderby c.pre ascending
                        select new CutomerType { CutomerTypeId = c.CutomerTypeId, CutomerTypeName = c.CutomerTypeName, LastId = c.LastId, pre = c.pre };
            return query.ToList();
        }


        public CutomerType SaveCutomerType(CutomerType c)
        {
            var item = (from ct in m_context.CutomerTypes
                        where ct.CutomerTypeId == c.CutomerTypeId
                        select ct).FirstOrDefault();
            if (CommonHelper.IsNull(item))
            {
                m_context.CutomerTypes.InsertOnSubmit(new Payroll.BusinessLogic.Data.CutomerType { CutomerTypeName = c.CutomerTypeName, LastId = 0, pre = c.pre, delete = false });
                m_context.SubmitChanges();
            }
            return c;
        }

        public int DelateCutomerType(int cutomerTypeId)
        {
            var item = (from ct in m_context.CutomerTypes
                        where ct.CutomerTypeId == cutomerTypeId
                        select ct).FirstOrDefault();
            if (!CommonHelper.IsNull(item))
            {
                item.delete = true;
                m_context.SubmitChanges();
            }
            return 1;
        }


        public CustomerSearchResult GetCustomerSearchResultbyId(int customerId)
        {
            var query = from cf in m_context.CustomerFilters
                        where cf.UserId == customerId
                        select new CustomerSearchResult
                        {
                            UserId = cf.UserId,
                            CustName = cf.CustName ?? "",
                            CustCaseWork = cf.CustCaseWork ?? "",
                            CustHour = cf.CustHour ?? "",
                            CustYearOfBirth = cf.CustYearOfBirth ?? "0",
                            CustMonthOfBirth = "0",
                            CustParent = cf.CustParent ?? "",
                            CustMobile = cf.CustMobile ?? "",
                            CustYear = cf.CustYear ?? cf.CustYear.Value,
                            CustMonth = cf.CustMonth ?? cf.CustYear.Value,
                            IsStudy = cf.IsStudy ?? cf.IsStudy.Value,
                            CustNationalId = cf.CustNationalId ?? cf.CustNationalId.Value,
                            CustCounselor = cf.CustCounselor ?? "",
                            CutomerTypeId = cf.CutomerTypeId ?? cf.CutomerTypeId.Value,
                            statusVisa = cf.statusVisa ?? cf.statusVisa.Value,
                            CustSchool = cf.CustSchool ?? "",
                            ProCurator = cf.ProCurator ?? ""
                        };
            return query.FirstOrDefault();
        }

        public void SaveCustomerFilter(CustomerSearchResult cf)
        {
            var item = (from c in m_context.CustomerFilters
                        where c.UserId == cf.UserId
                        select c).FirstOrDefault();

            if (CommonHelper.IsNull(item))
            {
                m_context.CustomerFilters.InsertOnSubmit(new CustomerFilter
                {
                    UserId = cf.UserId,
                    CustName = cf.CustName,
                    CustCaseWork = cf.CustCaseWork,
                    CustHour = cf.CustHour,
                    CustYearOfBirth = cf.CustYearOfBirth,
                    CustParent = cf.CustParent,
                    CustMobile = cf.CustMobile,
                    CustYear = cf.CustYear,
                    CustMonth = cf.CustMonth,
                    IsStudy = cf.IsStudy,
                    CustNationalId = cf.CustNationalId,
                    CustCounselor = cf.CustCounselor,
                    CutomerTypeId = cf.CutomerTypeId,
                    statusVisa = cf.statusVisa,
                    CustSchool = cf.CustSchool,
                    ProCurator = cf.ProCurator
                });
            }
            else
            {
                item.UserId = cf.UserId;
                item.CustName = cf.CustName;
                item.CustCaseWork = cf.CustCaseWork;
                item.CustHour = cf.CustHour;
                item.CustYearOfBirth = cf.CustYearOfBirth;
                item.CustParent = cf.CustParent;
                item.CustMobile = cf.CustMobile;
                item.CustYear = cf.CustYear;
                item.CustMonth = cf.CustMonth;
                item.IsStudy = cf.IsStudy;
                item.CustNationalId = cf.CustNationalId;
                item.CustCounselor = cf.CustCounselor;
                item.CutomerTypeId = cf.CutomerTypeId;
                item.statusVisa = cf.statusVisa;
                item.CustSchool = cf.CustSchool;
                item.ProCurator = cf.ProCurator;
            }
            m_context.SubmitChanges();
        }
        #region Dashboard
        public List<Dashboard> GetDashboardPassbook()
        {
            var query = from c in m_context.GetDashboardPassbook()
                        select new Dashboard
                        {
                            CustomerID = c.CustomerID,
                            CustCaseWork = c.CustCaseWork,
                            CustName = c.CustName,
                            CutomerTypeName = c.CutomerTypeName,
                            ProSchool = c.ProSchool,
                            ProCurator = c.ProCurator,
                            StatusVisa = c.StatusVisa,
                            ProDateOfAdmission = c.ProDateOfAdmission ?? "",
                            ProscheduledInterviewDate = c.ProscheduledInterviewDate ?? "",
                            UpdateBy = c.UpdateBy
                        };
            return query.ToList();
        }
        public List<Dashboard> GetDashboardInterviewDate()
        {
            var query = from c in m_context.GetDashboardInterviewDate()
                        select new Dashboard
                        {
                            CustomerID = c.CustomerID,
                            CustCaseWork = c.CustCaseWork,
                            CustName = c.CustName,
                            CutomerTypeName = c.CutomerTypeName,
                            ProSchool = c.ProSchool,
                            ProCurator = c.ProCurator,
                            StatusVisa = c.StatusVisa,
                            ProDateOfAdmission = c.ProscheduledInterviewDate ?? "",
                            ProscheduledInterviewDate = c.ProscheduledInterviewDate ?? "",
                            CustCounselor = c.CustCounselor,
                            UpdateBy = c.UpdateBy
                        };
            return query.ToList();
        }
        public List<Dashboard> GetDashboard()
        {
            var query = from c in m_context.GetDashboard()
                        select new Dashboard
                        {
                            CustomerID = c.CustomerID,
                            CustCaseWork = c.CustCaseWork,
                            CustName = c.CustName,
                            CutomerTypeName = c.CutomerTypeName,
                            ProSchool = c.ProSchool,
                            ProCurator = c.ProCurator,
                            StatusVisa = c.StatusVisa ?? "",
                            ProDateOfAdmission = c.ProDateOfAdmission ?? "",
                            ProscheduledInterviewDate = c.ProscheduledInterviewDate ?? "",
                            UpdateBy = c.UpdateBy
                        };
            return query.ToList();
        }
        public List<Dashboard> GetDashboardAppointment()
        {
            var query = from c in m_context.GetDashboardAppointment()
                        select new Dashboard
                        {
                            CustomerID = c.CustomerID,
                            CustCaseWork = c.CustCaseWork,
                            CustName = c.CustName,
                            CutomerTypeName = c.CutomerTypeName,
                            CustMobile = c.CustMobile ?? "",
                            FollowUpDate01 = c.FollowUpDate01 ?? "",
                            FollowUpDate02 = c.FollowUpDate02 ?? "",
                            FollowUpDate03 = c.FollowUpDate03 ?? "",
                            UpdateBy = c.UpdateBy
                        };
            return query.ToList();
        }
        public List<DashboardGenaral> GetDashboardGenaral()
        {
            var query = from c in m_context.GetDashboardGenaral()
                        select new DashboardGenaral
                        {
                            CustomerID = c.CustomerID,
                            CustName = c.CustName,
                            CustCaseWork = c.CustCaseWork,
                            CutomerTypeName = c.CutomerTypeName,
                            Addprofile = CommonHelper.Format(c.Addprofile),
                            AddprofileSchools = CommonHelper.Format(c.AddprofileSchools),
                            AddSeviceFreeSchools = CommonHelper.Format(c.AddSeviceFreeSchools),
                            Addhealthcare = CommonHelper.Format(c.Addhealthcare),
                            AddSeviceFree = CommonHelper.Format(c.AddSeviceFree),
                            AddI20offer = CommonHelper.Format(c.AddI20offer),
                            AddCheckI20offer = CommonHelper.Format(c.AddCheckI20offer),
                            Registrationticket = CommonHelper.Format(c.Registrationticket),
                            Registrationtaccommodation = CommonHelper.Format(c.Registrationtaccommodation),
                            Registrationairport = CommonHelper.Format(c.Registrationairport),
                            TransferSchool = CommonHelper.Format(c.TransferSchool)
                        };
            return query.ToList();
        }
        #endregion
        #region image

        private string SavePictureInFile(string pictureId, byte[] pictureBinary, string mimeType, string ImagePath)
        {
            string[] parts = mimeType.Split('/');
            string lastPart = parts[parts.Length - 1];
            switch (lastPart)
            {
                case "pjpeg":
                    lastPart = "jpg";
                    break;
                case "x-png":
                    lastPart = "png";
                    break;
                case "x-icon":
                    lastPart = "ico";
                    break;
            }
            string localFilename = string.Format("{0}_0.{1}", pictureId, lastPart);
            this.DeletePictureByPictureId(pictureId, ImagePath);
            SavePictureToImage(Path.Combine(ImagePath, localFilename), pictureBinary, this.LocalPicel, lastPart);

            //File.WriteAllBytes(Path.Combine(LocalImagePath, localFilename), pictureBinary);

            return CommonHelper.GetStoreLocation() + "images/Customer/" + localFilename; ;
        }
        private void SavePictureToImage(string localFilename, byte[] pictureBinary, int targetSize, string lastPart)
        {
            using (MemoryStream stream = new MemoryStream(pictureBinary))
            {
                var b = new Bitmap(stream);

                var newSize = CalculateDimensions(b.Size, targetSize);

                if (newSize.Width < 1)
                    newSize.Width = 1;
                if (newSize.Height < 1)
                    newSize.Height = 1;

                var newBitMap = new Bitmap(newSize.Width, newSize.Height);
                var g = Graphics.FromImage(newBitMap);
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                g.DrawImage(b, 0, 0, newSize.Width, newSize.Height);
                var ep = new EncoderParameters();
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, this.ImageQuality);
                ImageCodecInfo ici = GetImageCodecInfoFromExtension(lastPart);
                if (ici == null)
                    ici = GetImageCodecInfoFromMimeType("image/jpeg");
                newBitMap.Save(localFilename, ici, ep);
                newBitMap.Dispose();
                b.Dispose();
            }
        }
        public void DeletePictureByPictureId(string pictureId, string Local)
        {
            //delete thumbs
            string filter = string.Format("{0}*.*", pictureId);
            string[] currentFiles = System.IO.Directory.GetFiles(Local, filter);
            foreach (string currentFileName in currentFiles)
                File.Delete(Path.Combine(Local, currentFileName));


        }
        public void DeletePicture(string pictureId, string MimeType)
        {
            //delete thumbs
            string filter = string.Format("{0}*.*", pictureId);
            string[] currentFiles = System.IO.Directory.GetFiles(this.LocalThumbImagePath, filter);
            foreach (string currentFileName in currentFiles)
                File.Delete(Path.Combine(this.LocalThumbImagePath, currentFileName));

            //delete from file system
            DeletePictureOnFileSystem(pictureId, MimeType);
        }
        private void DeletePictureOnFileSystem(string pictureId, string MimeType)
        {
            if (MimeType == null)
                throw new ArgumentNullException("picture");

            string[] parts = MimeType.Split('/');
            string lastPart = parts[parts.Length - 1];
            switch (lastPart)
            {
                case "pjpeg":
                    lastPart = "jpg";
                    break;
                case "x-png":
                    lastPart = "png";
                    break;
                case "x-icon":
                    lastPart = "ico";
                    break;
            }
            string localFilename = string.Format("{0}_0.{1}", pictureId, lastPart);
            string localFilepath = Path.Combine(LocalImagePath, localFilename);
            if (File.Exists(localFilepath))
            {
                File.Delete(localFilepath);
            }
        }
        /// <summary>
        /// Calculates picture dimensions whilst maintaining aspect
        /// </summary>
        /// <param name="originalSize">The original picture size</param>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <returns></returns>
        private Size CalculateDimensions(Size originalSize, int targetSize)
        {
            var newSize = new Size();
            if (originalSize.Height > originalSize.Width) // portrait 
            {
                newSize.Width = (int)(originalSize.Width * (float)(targetSize / (float)originalSize.Height));
                newSize.Height = targetSize;
            }
            else // landscape or square
            {
                newSize.Height = (int)(originalSize.Height * (float)(targetSize / (float)originalSize.Width));
                newSize.Width = targetSize;
            }
            return newSize;
        }
        /// <summary>
        /// Loads a cpiture from file
        /// </summary>
        /// <param name="pictureId">Picture identifier</param>
        /// <param name="mimeType">MIME type</param>
        /// <returns>Picture binary</returns>
        public byte[] LoadPictureFromFile(string pictureId, string mimeType)
        {
            string[] parts = mimeType.Split('/');
            string lastPart = parts[parts.Length - 1];
            switch (lastPart)
            {
                case "pjpeg":
                    lastPart = "jpg";
                    break;
                case "x-png":
                    lastPart = "png";
                    break;
                case "x-icon":
                    lastPart = "ico";
                    break;
            }
            string localFilename = string.Empty;
            localFilename = string.Format("{0}_0.{1}", pictureId, lastPart);
            if (!File.Exists(Path.Combine(LocalImagePath, localFilename)))
            {
                return new byte[0];
            }
            return File.ReadAllBytes(Path.Combine(LocalImagePath, localFilename));
        }
        /// <summary>
        /// Returns the first ImageCodecInfo instance with the specified mime type.
        /// </summary>
        /// <param name="mimeType">Mime type</param>
        /// <returns>ImageCodecInfo</returns>
        private ImageCodecInfo GetImageCodecInfoFromMimeType(string mimeType)
        {
            var info = ImageCodecInfo.GetImageEncoders();
            foreach (var ici in info)
                if (ici.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase))
                    return ici;
            return null;
        }
        /// <summary>
        /// Returns the first ImageCodecInfo instance with the specified extension.
        /// </summary>
        /// <param name="fileExt">File extension</param>
        /// <returns>ImageCodecInfo</returns>
        private ImageCodecInfo GetImageCodecInfoFromExtension(string fileExt)
        {
            fileExt = fileExt.TrimStart(".".ToCharArray()).ToLower().Trim();
            switch (fileExt)
            {
                case "jpg":
                case "jpeg":
                    return GetImageCodecInfoFromMimeType("image/jpeg");
                case "png":
                    return GetImageCodecInfoFromMimeType("image/png");
                case "gif":
                    //use png codec for gif to preserve transparency
                    //return GetImageCodecInfoFromMimeType("image/gif");
                    return GetImageCodecInfoFromMimeType("image/png");
                default:
                    return GetImageCodecInfoFromMimeType("image/jpeg");
            }
        }
        #endregion
        #region Relationship
        public void SaveRelationship(List<Relationships> List, int customerId)
        {
            bool flag = false;
            List<Relationship> InsertOnSubmit = new List<Relationship>();
            foreach (var info in List)
            {
                if (!flag)
                {
                    flag = true;
                }
                InsertOnSubmit.Add(new Relationship { RelationshipID = customerId, CustomerID = info.CustomerID });
            }
            if (flag)
            {
                var query = from r in m_context.Relationships
                            where r.RelationshipID == customerId
                            select r;
                if (!CommonHelper.IsNull(query))
                {
                    m_context.Relationships.DeleteAllOnSubmit(query);
                }
                m_context.Relationships.InsertAllOnSubmit(InsertOnSubmit);
                m_context.SubmitChanges();
            }
        }
        public List<Relationships> GetListRelationship(int customerId)
        {
            var query = from r in m_context.Relationships
                        join c in m_context.Customers on r.CustomerID equals c.CustomerID into CustJoin
                        from o2 in CustJoin.DefaultIfEmpty()
                        where r.RelationshipID == customerId
                        select new Relationships
                        {
                            RelationshipID = customerId,
                            CustomerID = r.CustomerID,
                            CustName = o2.CustName,
                            CustCaseWork = o2.CustCaseWork,
                            CustMobile = o2.CustMobile ?? "",
                            ProCurator = o2.ProCurator ?? "",
                            CustCounselor = o2.CustCounselor ?? ""
                        };
            return query.ToList();
        }
        public List<Customer> GetNotRelationship(CustomerSearchResult cust, int customerId)
        {
            var query = from c in m_context.GetRelationship(customerId, cust.CustName, cust.CustCaseWork, cust.CustHour, cust.CustMobile, cust.CustParent, cust.CustCounselor, cust.ProCurator, cust.CutomerTypeId)
                        select new Customer
                        {
                            CustCaseWork = c.CustCaseWork,
                            CustName = c.CustName,
                            CustomerID = c.CustomerID,
                            CustMobile = c.CustMobile,
                            CustParent = c.CustParent,
                            ProCurator = c.ProCurator,
                            CustCounselor = c.CustCounselor
                        };
            return query.ToList();
        }
        #endregion
    }
}
